package com.ec.auth.security.handle;

import com.ec.auth.manager.AsyncManager;
import com.ec.auth.manager.factory.AsyncFactory;
import com.ec.auth.web.service.TokenService;
import com.ec.common.constant.Constants;
import com.ec.common.core.domain.AjaxResult;
import com.ec.common.core.domain.model.LoginUser;
import com.ec.common.utils.ServletUtils;
import com.ec.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
public class LogoutSuccessHandle implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = tokenService.getToken(request);
        if (token != null) {
            LoginUser loginUser;
            try {
                loginUser = tokenService.getLoginUser(token);
            } catch (Exception e) {
                ServletUtils.renderFailString(response, AjaxResult.success("退出登录成功！"));
                return;
            }
            if (StringUtils.isNotNull(loginUser)) {
                // 删除用户的缓存
                tokenService.delLoginUser(loginUser.getToken());
                String tenant = request.getHeader("tenant");
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(tenant, loginUser.getUsername(), Constants.LOGOUT, "退出成功"));
            }
        }
        ServletUtils.renderFailString(response, AjaxResult.success("退出登录成功！"));
    }
}

